﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Newtonsoft.Json.Linq
{
    public static class JObjectExtensions
    {
        /// <summary>
        /// 获取JObject对象的属性值，属性不存在则返回该值的类型的默认值。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T Get<T>(this JObject obj, string key)
        {
            if (obj == null)
            {
                return default(T);
            }
            var v = obj[key];
            return v == null ? default(T) : v.ToObject<T>();
        }
        public static string GetString(this JObject obj, string key)
        {
            if (obj == null)
            {
                return null;
            }
            var v = obj[key];
            return v == null ? null : v.ToString();
        }
        public static int GetInt32(this JObject obj, string key)
        {
            if (obj == null)
            {
                return default(int);
            }
            var v = obj[key];
            return v == null ? default(int) : v.ToObject<int>();
        }
        public static double GetDouble(this JObject obj, string key)
        {
            if (obj == null)
            {
                return default(double);
            }
            var v = obj[key];
            return v == null ? default(double) : v.ToObject<double>();
        }
        public static bool GetBoolean(this JObject obj, string key)
        {
            if (obj == null)
            {
                return default(bool);
            }
            var v = obj[key];
            return v == null ? default(bool) : v.ToObject<bool>();
        }
        public static DateTime GetDateTime(this JObject obj, string key)
        {
            if (obj == null)
            {
                return default(DateTime);
            }
            var v = obj[key];
            return v == null ? default(DateTime) : v.ToObject<DateTime>();
        }
        public static T[] GetArray<T>(this JObject obj, string key)
        {
            return Get<T[]>(obj, key);
            //if (obj == null)
            //{
            //    return null;
            //}
            //var v = obj[key];
            //if (v==null)
            //{
            //    return null;
            //}
            //if (v is JArray arr)
            //{
            //    List<T> l = new List<T>();
            //    foreach (var item in arr)
            //    {
            //        l.Add(item.ToObject<T>());
            //    }
            //    return l.ToArray();
            //}
            //throw new ArrayTypeMismatchException("当前对象无法读取为数组。");
        }

    }
}
